package cn.kwq.project_manger.utils;

import cn.kwq.project_manger.exception.CodeErrorException;
import com.alibaba.fastjson2.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WechatUtils {

    @Value("${WeChat.APPID}")
    private  String APPID;
    @Value("${WeChat.SECRET}")
    private String SECRET;
    @Value("${WeChat.GRANT_TYPE}")
    private String GRANT_TYPE;

    @Value("${WeChat.WX_OPENID_URL}")
    private String WX_OPENID_URL;

    /**
     * 得到openId
     * @param code  前端传入 用户授权码
     * @return
     */
    public String getOpenId(String code) throws CodeErrorException {
        String openId = null;
        String param = "appid="+APPID+"&secret="+SECRET+"&js_code="+code+"&grant_type="+GRANT_TYPE;
        String requsetURL = WX_OPENID_URL + "?" + param;
        String response = HttpRequest.get(requsetURL).body();

        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.containsKey("errcode")) {
            log.error("请求微信服务器错误");
            throw new CodeErrorException();
        }
        openId = jsonObject.get("openid").toString();
        log.info("请求微信服务器成功");
        return openId ;
    }

}
